package com.example.shoporder.service.impl;


import com.example.shopcommon.entity.Order;
import com.example.shopcommon.entity.Product;
import com.example.shoporder.dao.OrderDao;
import com.example.shoporder.service.OrderService;
import com.example.shoporder.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * @author kw
 * @program springcloud-alibaba
 * @description
 * @create 2024 - 06 - 08 18:26
 **/
@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private OrderDao orderDao;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private ProductService productService;

    @Override
    public Order createOrder(Integer productId) {
        // 默认选择第一个，但实际业务中可能注册很多个实例，需随机选择
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance serviceInstance = instances.get(0);
//        int index = new Random().nextInt(instances.size());
//        ServiceInstance serviceInstance = instances.get(index);
//        Product product = restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId, Product.class);
        // ribbon 负载均衡
//        Product product = restTemplate.getForObject("http://service-product/product/" + productId, Product.class);

        // feign
        Product product = productService.findByProductId(productId);

        Order order = new Order();
        order.setNumber(1);
        order.setProductId(product.getId());
        order.setProductName(product.getProductName());
        order.setProductPrice(product.getPrice());
        order.setUserName("测试");
        // 若异常
        if (-1 == product.getId()) {
            order.setNumber(-1);
        }
        orderDao.save(order);
        return order;
    }
}
